<?php namespace Framework\Tool;

class Cache{
	//缓存目录
	public $dir;

	public function __construct($dir='cache')
	{
		$this->dir = $dir;
		//创建缓存目录
		is_dir($this->dir) or mkdir($this->dir,0777,true);
	}
	
	//获取缓存文件
	private function getFile($name)
	{
		return $this->dir.'/'.md5($name).'.php';
	}

	//检测缓存是否有效
	public function has($name)
	{
		$file = $this->getFile($name);
		if(is_file($file))
		{
			$content = file_get_contents($file);
			$time = substr($content,32,10);

			//在缓存期内
			if(filemtime($file)+$time>time())
			{
				return true;
			}
		}
		return false;
	}

	//设置缓存
	public function set($name,$value,$expire=3600)
	{
		$file = $this->getFile($name);
		
		//缓存过期时间
		$expire = str_pad ( $expire ,  10 ,  "0" ,  STR_PAD_LEFT );
			//保存缓存数据
		$data = '<?php if(!defined("HD"))exit;?>'.PHP_EOL.
		$expire.PHP_EOL.serialize($value);

		return file_put_contents($file,$data);
		
	}

	//获取缓存数据
	public function get($name)
	{
		if($this->has($name))
		{
			$file = $this->getFile($name);
			$data  =file_get_contents($file);	
			$data =substr($data,43);

			return unserialize($data);
		}
	}
	//删除一个缓存数据
	public function del($name)
	{
		$file = $this->getFile($name);
		if(is_file($file))
		{
			return unlink($file);
		}
		return true;
	}
	//全删除
	public function flush()
	{
		foreach (glob($this->dir.'/*.*') as $file) {
			if(is_file($file) && @unlink($file))
			{
				return false;
			}
		}
		return true;
	}
}







